import { useState, useEffect } from "react";
import { PageCommon, Common } from 'UtilsCommon';

const getUserId = () => {
    let sid = Common.getStorage('serialId');
    if (!sid) {
        sid = window.btoa(Common.createGuid());
        Common.setStorage('serialId', sid);
    }
    return { sid };
};

export default (pageAxis) => {
    const [user, setUser] = useState(window.visitUser);

    useEffect(() => {
        if (!user && pageAxis) {
            let { sid } = pageAxis.pageData;
            if (!sid) {
                const obj = getUserId();
                sid = obj.sid;
            }

            pageAxis.dispatchAction('VisitUserService', 'getUserInfo', { VisitUser2: { Serial: sid, MeetingRoomId: pageAxis.pageData.mid } }).then(res => {
                if (res.isSuccess === false) PageCommon.alert(res.message);
                else {
                    res.sid = sid;
                    pageAxis.visitUser = res;
                    pageAxis.theme = res.Theme;
                    window.visitUser = res;
                    setUser(pageAxis.visitUser);
                }
            });
        }
    }, [user, setUser, pageAxis]);

    if (user && pageAxis && !pageAxis.visitUser) {
        pageAxis.visitUser = user;
        pageAxis.theme = user.Theme;
    }

    return user;
};
